﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace DBUtil.FastEntity
{
    public class ExpressionParseContext
    {
        /// <summary>
        /// 当前表达式
        /// </summary>
        public Expression Expression { get; set; }

        /// <summary>
        /// 顶部的表达式的参数
        /// </summary>
        public ParameterExpression Parameter => Parent?.Parameter ?? SelfParameter;

        /// <summary>
        /// 仅在顶部赋值
        /// </summary>
        public ParameterExpression SelfParameter { set; get; }

        /// <summary>
        /// 表达式的一系列父节点
        /// </summary>
        public List<ExpressionParseContext> Parents { get; set; } = new List<ExpressionParseContext>();

        /// <summary>
        /// 子节点公共容器，里面存放的内容和顺序由NodeType决定
        /// </summary>
        public List<ExpressionParseContext> Children { set; get; } = new List<ExpressionParseContext>();

        /// <summary>
        /// 暂存生成的sql
        /// </summary>
        public string SqlCache { set; get; }

        /// <summary>
        /// 自己使用的别名
        /// </summary>
        public string SelfAlias { get; set; }

        /// <summary>
        /// 整个树使用的别名
        /// </summary>
        public string Alias => Parent?.Alias ?? SelfAlias;

        /// <summary>
        /// 表达式类型
        /// </summary>
        public ExpressionType NodeType => Expression.NodeType;

        /// <summary>
        /// 父节点
        /// </summary>
        public ExpressionParseContext Parent => Parents.LastOrDefault();

        /// <summary>
        /// 返回类型
        /// </summary>
        public Type ReturnType => Expression.Type;

        #region 是否有参数
        public bool HasParameter => SelfHasParameter || ChildrenHasParameter;
        public bool SelfHasParameter { set; get; }
        public bool ChildrenHasParameter => Children.Any(i => i.HasParameter);
        #endregion
    }
}
